package hello.world;

import android.content.Context;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class HelloWorldRenderer implements GLSurfaceView.Renderer
{
    private Context context = null;
    private final SpritesHolder spritesHolder;

    private void load(GL10 gl)
    {
        synchronized (spritesHolder)
        {
            spritesHolder.anime = new Sprite();
            spritesHolder.anime.loadTexture(R.drawable.anime, gl, context);
            spritesHolder.skull = new Sprite();
            spritesHolder.skull.loadTexture(R.drawable.skull, gl, context);
            
            spritesHolder.setLoaded();
        }
    }
    
    public HelloWorldRenderer(Context _context, SpritesHolder _spritesHolder)
    {
        context = _context;
        spritesHolder = _spritesHolder;
    }
    
    public void onSurfaceCreated(GL10 gl, EGLConfig config)
    {
        load(gl);
        
        gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glDisable(GL10.GL_DEPTH_TEST);
        gl.glDisable(GL10.GL_CULL_FACE);
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    }
    
    public void onDrawFrame(GL10 gl)
    {
        synchronized (spritesHolder)
        {
            gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            gl.glMatrixMode(GL10.GL_MODELVIEW);
            spritesHolder.anime.draw(gl);
            spritesHolder.skull.draw(gl);
        }
    }
    
    public void onSurfaceChanged(GL10 gl, int width, int height)
    {
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        float tmp = 384.0f * (float)width / (float)height;
        gl.glOrthof(-tmp, tmp, 768.0f, 0.0f, -1.0f, 1.0f);
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
    }
}
